import json
import logging
import time

import requests

from djco.base.base import Base
from djco.util.common_log import CommonLog

logger = logging.getLogger(__name__)
"""
    网络请求工具类型
    https://docs.python-requests.org/en/master/
"""


def http_json(url, params={}, methods='POST', headers={}, timeout=5):
    """
     post 或者 get  返回json
    :param url: url
    :param params: 参数
    :param methods: POST/GET
    :param headers: headers
    :param timeout: 接口超时
    :return: {err_code:0,err_msg:'',data:返回的json}
    """
    try:
        begin = time.time()
        if 'get' == methods.lower():
            r = requests.get(url, params=params, headers=headers, timeout=timeout)
        else:
            r = requests.post(url, data=params, headers=headers, timeout=timeout)

        if r.status_code == 200:
            if "json" in r.headers['content-type']:
                try:
                    res = r.json()
                except Exception as e:
                    return Base.api_ajax_error({}, "(invalid json body:" + r.text + ")")
            else:
                res = r.text
            return Base.api_ajax_success(res)
        else:
            return Base.api_ajax_error({}, url + "(request error code:" + str(r.status_code) + ")")
    except requests.exceptions.Timeout:
        return Base.api_ajax_error({}, url + "(request timed out)")
    except requests.exceptions.ConnectionError:
        return Base.api_ajax_error({}, url + "(failed to establish a new connection)")
    finally:
        end = time.time()
        CommonLog(logger).error(
            json.dumps(
                {'url': url, 'params': params, 'methods': methods, 'cost': round(end - begin, 2),
                 'res': __json_loads(r.text.strip())},
                ensure_ascii=False))


def __json_dumps(dict_data):
    try:
        return json.dumps(dict_data, ensure_ascii=False)
    except Exception as e:
        return dict_data


def __json_loads(str_data):
    try:
        return json.loads(str_data)
    except Exception as e:
        return str_data
